/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Mar 13, 2012  6:51:11 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.mm.inbound
 * File Name : MmSuppdebitnotesinbServices.java
 * TODO
 */
package sap.business.mm.inbound;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;

import jpa.entitys.synchro.common.ACTION_HANDLER;
import jpa.entitys.synchro.staging.MmSuppdebitnotesinb;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.MmSuppdebitnotesinbServices;

import org.apache.log4j.Logger;

import promis.utility.CommonService;
import sap.business.commons.services.CommonJCOReturn;
import apps.promis.in.construction.AccountPayableVoucherAction;
import apps.promis.in.construction.SupplierDebitNoteServicesAction;

import com.sap.mw.jco.JCO;

/**
 * @author Chatree Siangklom of Administrator
 * Date =Nov 12, 2013 : 2:04:30 PM 
 * CreateBy=Chatree Siangklom
 * 
 * MmSuppdebitnotesinbService
 * TODO
 */
public class MmSuppdebitnotesinbService {
	
	private static final Logger log = Logger.getLogger(MmSuppdebitnotesinbService.class);

	/**
	 * Date =Nov 12, 2013 : 2:05:13 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @param input
	 * @param tables
	 * @param output
	 * @param structureOrTableName
	 * @throws Exception
	 */
	public void CreatedSync(JCO.ParameterList input, JCO.ParameterList tables, JCO.ParameterList output, String structureOrTableName) throws Exception {
		List<MmSuppdebitnotesinb> lst = null;
		List<MmSuppdebitnotesinb> lst_object = new ArrayList<MmSuppdebitnotesinb>();
		JCO.Table table = tables.getTable(structureOrTableName);
		int records = -1;
		try{
			
			records = table.getNumRows();
			EntityManager em = new SessionEntityManager().CreatedEntityManager();
			MmSuppdebitnotesinbServices mmSuppdebitnotesinbsServ = new MmSuppdebitnotesinbServices(em);			
			String instance_no = mmSuppdebitnotesinbsServ.GetNewInstanceNo();
			
			for(int i = 0; i < records; i++)
			{
				log.info("i ="+ i);
				table.setRow(i);			
				MmSuppdebitnotesinb model = new MmSuppdebitnotesinb();
				model.setInstanceNo(instance_no);
				model.setInterfaceNo("MM-T2-020");
				//model.setPromisStagingId(CommonService.IsNullRNull(table.getString("PROMIS_TXN_ID")));				
				model.setSapCompanyCode(CommonService.IsNullRNull(table.getString("SAP_COMPANY_CODE")));
				model.setSapPlantCode(CommonService.IsNullRNull(table.getString("SAP_PANT_CODE")));
				model.setLivDoc(CommonService.IsNullRNull(table.getString("LIV_DOC")));
				model.setSupplierReference(CommonService.IsNullRNull(table.getString("SUPPLIER_REF")));
				model.setVoucherType(CommonService.IsNullRNull(table.getString("VOUCHER_TYPE")));
				model.setDocDate(CommonService.IsNullRNull(table.getString("DOC_DATE")));								
				//model.setVoucherSeries(CommonService.IsNullRNull(table.getString("VOUCHER_SERIES")));	//don't send
				//model.setVoucherNumber(CommonService.IsNullRNull(table.getString("VOUCHER_NUMBER")));	//don't send
				//model.setSeqNo(new BigDecimal(CommonService.IsNullRZero(table.getString("SEQ_NO")))); //don't send
				model.setSupplierCode(CommonService.IsNullRNull(table.getString("SUPPLIER_CODE")));
				model.setNetAmount(CommonService.IsNullRNull(table.getString("SUPPLIER_AMOUNT")));
				model.setTaxType(CommonService.IsNullRNull(table.getString("TAX_TYPE")));
				model.setCostOfGoodsLocal(CommonService.IsNullRNull(table.getString("COST_OF_GOODS")));
				model.setVatAmountH(CommonService.IsNullRNull(table.getString("VAT_AMOUNT")));
				model.setStatus(CommonService.IsNullRNull(table.getString("STATUS")));
				
				//model.setBuildingPhase(CommonService.IsNullRNull(table.getString("BUILDING_PHASE")));
				//model.setZoneCode(CommonService.IsNullRNull(table.getString("ZONE_CODE")));
				model.setUnitNumber(CommonService.IsNullRNull(table.getString("UNIT_NUMBER")));
				model.setRefNo(CommonService.IsNullRNull(table.getString("REF_NO")));
				model.setGrnSeqNo(CommonService.IsNullRNull(table.getString("GRN_SEQ_NO")));
				model.setExtPoNo(CommonService.IsNullRNull(table.getString("EXT_PO_NO")));
				
				model.setExtPoSeq(CommonService.IsNullRNull(table.getString("EXT_PO_SEQ")));  
				model.setItemCode(CommonService.IsNullRNull(table.getString("ITEM_CODE")));
				model.setQuantity(CommonService.IsNullRNull(table.getString("QUANTITY")));
				model.setCostBfVat(CommonService.IsNullRNull(table.getString("COST_BF_VAT")));
				model.setTotalCost(CommonService.IsNullRNull(table.getString("TOTAL_COST")));				
				
				//Set Txn Reacord				
				model.setCreatedOn(CommonService.IsNullRNull(table.getString("CREATED_ON")));
				model.setCreatedBy(CommonService.IsNullRNull(table.getString("CREATED_BY")));
				model.setUpdatedOn(CommonService.IsNullRNull(table.getString("LAST_UPD_ON")));
				model.setUpdatedBy(CommonService.IsNullRNull(table.getString("LAST_UPD_BY")));
				
				if(CommonService.IsNull(table.getString("LAST_UPD_ON")))
					model.setActionHandler(ACTION_HANDLER.INSERTED.toString());				
				else 
					model.setActionHandler(ACTION_HANDLER.UPDATED.toString());
				
				//Set SAP External Key link
				model.setExtRefKey(CommonService.IsNullRNull(table.getString("SYNC_EXTERNAL_REF_KEY")));				
				model.setExtRefNo(CommonService.IsNullRNull(table.getString("SYNC_EXTERNAL_REF_NO")));
				if(CommonService.IsNull(model.getExtRefNo()))
					model.setExtRefNo(model.getLivDoc());
				
				lst_object.add(model);		
			}
			
			//INSERT
			mmSuppdebitnotesinbsServ.Inserted(lst_object);
			
			lst = mmSuppdebitnotesinbsServ.findByInstanceNo(instance_no);
			
			if(CommonService.getSize(lst) > 0)
			{
				//Create To Promis
				if(lst.get(0).getVoucherType().equals("AP")) //Account Payable (AP)
					new AccountPayableVoucherAction().CreateToPromis(lst);
				else if(lst.get(0).getVoucherType().equals("57")) //Credit Note (CN)
					new SupplierDebitNoteServicesAction().CreateToPromis(lst);
				
				if(CommonService.getSize(lst) == records){
					for(int i = 0; i < records; i++)
					{
						MmSuppdebitnotesinb obj = lst.get(i);
						table.setRow(i);
						table.setValue(CommonService.IsNullRString(obj.getPromisStagingId()), "PROMIS_TXN_ID");
						table.setValue("S", "MSG_CODE");
						table.setValue("Success", "MSG_DESC");
						table.setValue(obj.getExtRefNo(), "MSG_ALT_DESC");
						table.setValue("", "MSG_ACTION_RESULT");	
						log.info(CommonJCOReturn.toString(table));
					}
				}
			}else {				
				System.err.println("find not found  instance no=" + instance_no);
				log.info("find not found  instance no=" + instance_no);
			}				
		}
		catch(Exception e)
		{	
			System.err.println(e.getMessage());
			log.error(e.getMessage());			
			if(CommonService.getSize(lst) > 0){
				
					if(CommonService.getSize(lst) == records){
						for(int i = 0; i < records; i++)
						{
							MmSuppdebitnotesinb obj = lst.get(i);
							table.setRow(i);
							table.setValue(CommonService.IsNullRString(obj.getPromisStagingId()), "PROMIS_TXN_ID");
							table.setValue("E", "MSG_CODE");
							table.setValue(e.getMessage(), "MSG_DESC");
							table.setValue(obj.getExtRefNo(), "MSG_ALT_DESC");
							table.setValue("", "MSG_ACTION_RESULT");
							log.info(CommonJCOReturn.toString(table));
						}
					}			
			}else{			
				for(int i = 0; i < records; i++)
				{
					table.setRow(i);
					table.setValue("E", "MSG_CODE");
					table.setValue(e.getMessage(), "MSG_DESC");
				}
			}
		}finally{
			System.out.println("End of Liv --------------------> ");
			log.info("End of Liv --------------------> ");
		}
	}
}
